package com.liu.service.impl;

import com.liu.controller.dto.PasswordDTO;
import com.liu.controller.dto.UserDTO;
import com.liu.mapper.AdminMapper;
import com.liu.entity.Admin;
import com.liu.service.AdminService;
import com.liu.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Map;

@Service("AdminServiceImpl")
@Transactional
public class AdminServiceImpl implements AdminService {
    @Resource
    private AdminMapper adminMapper;


    @Autowired
    public void setAdminMapper(AdminMapper adminMapper){
        this.adminMapper = adminMapper;
    }

    @Override
    public Admin findAdmin(String username) {
        Admin admin = this.adminMapper.findAdmin(username);
        return admin;
    }

    @Override
    public Admin login(Map<String, Object> map) {
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        Admin admin = adminMapper.findAdmin(username);
        if(admin == null) throw new RuntimeException("用户名输入错误，请重新输入");
        if (!admin.getPassword().equals(password)) throw new RuntimeException("密码输入错误！");
        String token = TokenUtils.genToken(admin.getId().toString(), admin.getPassword());
        admin.setToken(token);
        return admin;
    }

    private Admin getUserInfo(UserDTO userDTO) {
        Admin one;
        try {
            one = findAdmin(userDTO.getUsername()); // 从数据库查询用户信息
        } catch (Exception e) {
            throw new RuntimeException("系统错误");
        }
        return one;
    }

    @Override
    public int addAdmin(Admin admin) {
        return adminMapper.addAdmin(admin);
    }

    @Override
    public Admin queryAdminById(int id) {
        return adminMapper.queryAdminById(id);
    }

    @Override
    public int updateAdmin(Admin admin) {
        return adminMapper.updateAdmin(admin);
    }

    @Override
    public int updatePwd(PasswordDTO passwordDTO) {
        return adminMapper.updatePwd(passwordDTO);
    }
}
